//
//  MDSplashScreenManager.swift
//  MDPreviewImageTest
//
//  Created by Alan on 2018/1/10.
//  Copyright © 2018年 MD. All rights reserved.
//

import UIKit

public let AdImageName = "AdImageName"
public let AdGifName = "AdGifName"
public let AdViedioName = "AdViedioName"
public let AdLinkUrl = "AdLinkUrl"
public let AdValidTime = "AdValidTime"


open class MDSplashScreenManager: NSObject {
    
    public static let sharedManager = MDSplashScreenManager()
    
    fileprivate override init() {}
    
    
    open func isFileExistWithFilePath(filePath:String)->Bool{
        let fileManager = FileManager.default
        var directory: ObjCBool = ObjCBool(false)
        return fileManager.fileExists(atPath: filePath, isDirectory: &directory)
    }
    
    open func getAdvertisingData(url:String,validTime:String,linkUrl:String,type:MDSplashScreenType){
        // 获取名称
        let stringArr = url.components(separatedBy: "/")
        let name: String? = stringArr.last
        // 拼接沙盒路径
        let filePath: String = getFilePathWithName(name: name!)
        let isExist: Bool = isFileExistWithFilePath(filePath: filePath)
        if !isExist {
            // 如果该资源不存在，则删除老的，下载新的
            if type == .netImage{
                downloadAdDataWithUrl(url: url, name: name!, linkUrl: linkUrl, validTime: validTime,key: AdImageName)
            }else if type == .netGif{
                downloadAdDataWithUrl(url: url, name: name!, linkUrl: linkUrl, validTime: validTime,key: AdGifName)
            }else if type == .netVidio{
                downloadAdDataWithUrl(url: url, name: name!, linkUrl: linkUrl, validTime: validTime,key: AdViedioName)
            }
        }
    }

    //下载资源到本地
    fileprivate func downloadAdDataWithUrl(url:String,name:String,linkUrl:String,validTime:String,key:String){
        DispatchQueue.global().async {
            let data = try? Data.init(contentsOf: URL(string: url)!)
            if data != nil{
                let filePath  = self.getFilePathWithName(name: name)
                let gifData = NSData.init(data: data!)
                let isWrite = gifData.write(toFile: filePath, atomically: true)
                print(filePath)
                if isWrite{
                    let adImageName:String? = UserDefaults.standard.object(forKey: key) as? String
                    if name == adImageName{
                        self.deleteOldCache()
                    }
                    UserDefaults.standard.setValue(name, forKey: key)
                    UserDefaults.standard.setValue(linkUrl, forKey: AdLinkUrl)
                    UserDefaults.standard.setValue(validTime, forKey: AdValidTime)
                    UserDefaults.standard.synchronize()
                }else{
                    print("保存失败")
                }
            }else{
                print("图片Data为空，请检查您的网络或图片链接")
            }
        }
    }
    
    //删除旧的缓存文件
    fileprivate func deleteOldCache(){
        let imageName:String? = UserDefaults.standard.value(forKey: AdImageName) as? String
        let viedioName:String? = UserDefaults.standard.value(forKey: AdViedioName) as? String
        let gifName:String? = UserDefaults.standard.value(forKey: AdGifName) as? String
        
        if imageName != nil{
            let filePath = self.getFilePathWithName(name: imageName!)
            let fileManager = FileManager.default
            try? fileManager.removeItem(atPath: filePath)
            UserDefaults.standard.setValue("", forKey: AdImageName)
            UserDefaults.standard.setValue("", forKey: AdLinkUrl)
            UserDefaults.standard.setValue("", forKey: AdValidTime)
            UserDefaults.standard.synchronize()
        }
        if gifName != nil{
            let filePath = self.getFilePathWithName(name: gifName!)
            let fileManager = FileManager.default
            try? fileManager.removeItem(atPath: filePath)
            UserDefaults.standard.setValue("", forKey: AdGifName)
            UserDefaults.standard.setValue("", forKey: AdLinkUrl)
            UserDefaults.standard.setValue("", forKey: AdValidTime)
            UserDefaults.standard.synchronize()
        }
        if viedioName != nil{
            let filePath = self.getFilePathWithName(name: viedioName!)
            let fileManager = FileManager.default
            try? fileManager.removeItem(atPath: filePath)
            UserDefaults.standard.setValue("", forKey: AdViedioName)
            UserDefaults.standard.setValue("", forKey: AdLinkUrl)
            UserDefaults.standard.setValue("", forKey: AdValidTime)
            UserDefaults.standard.synchronize()
        }
    }
    
    
    open func getFilePathWithName(name:String) -> String{
        print(NSHomeDirectory())
        let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last
        let filePath: String = paths!.appending(name)
        return filePath
    }
}
